package com.authentication.center.common;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.Base64Utils;
import sun.security.rsa.RSAPrivateCrtKeyImpl;
import sun.security.rsa.RSAPublicKeyImpl;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * 生成RSA 的公钥、私钥对
 *
 * @author : garvin
 * @version V1.0
 * @date : 2020年10月20日 17:20
 */
@Slf4j
@Component
public class LoadKey {

    private KeyPair keyPair;

    public LoadKey() {
        try {
            byte[] bytePublicKey = IOUtils.toByteArray(getClass().getResourceAsStream("/key/rsa.public"));
            byte[] bytePrivateKey = IOUtils.toByteArray(getClass().getResourceAsStream("/key/rsa.private"));

            PublicKey rsaPublicKey = new RSAPublicKeyImpl(Base64Utils.decode(bytePublicKey));
            PrivateKey rsaPrivateKey = RSAPrivateCrtKeyImpl.newKey(Base64Utils.decode(bytePrivateKey));

            keyPair = new KeyPair(rsaPublicKey, rsaPrivateKey);
        } catch (Exception e) {
            log.error("Generator RSA Key Error.", e);
        }
    }

    public KeyPair getKeyPair() {
        Assert.notNull(keyPair, "keyPair is null");
        return keyPair;
    }

    public static void main(String[] args) {
        new LoadKey();
    }
}
